<template>
  <div class="flash-sale-container">
    <!-- 抢购头部 -->
    <div class="sale-header">
      <h2>限时抢购</h2>
      <div class="countdown">
        <span class="countdown-title">距{{ saleStatus === 'coming' ? '开始' : '结束' }}:</span>
        <span class="countdown-block">{{ hours }}</span>
        <span class="countdown-colon">:</span>
        <span class="countdown-block">{{ minutes }}</span>
        <span class="countdown-colon">:</span>
        <span class="countdown-block">{{ seconds }}</span>
      </div>
      <div class="sale-status">{{ statusText }}</div>
    </div>

    <!-- 抢购场次 -->
    <div class="sale-sessions">
      <div 
        v-for="session in sessions" 
        :key="session.id"
        :class="{ 
          active: currentSession.id === session.id,
          disabled: session.disabled
        }"
        @click="!session.disabled && switchSession(session)"
      >
        {{ session.name }}<br>
        <small>{{ session.timeRange }}</small>
      </div>
    </div>

    <!-- 抢购商品列表 -->
    <div class="sale-products">
      <div 
        v-for="product in currentSession.products" 
        :key="product.id"
        class="sale-product"
        :class="{ disabled: isProductDisabled(product) }"
      >
        <div class="product-image">
          <img :src="product.productMainImg" :alt="product.productName">
          <div class="sale-tag">限时抢购</div>
          <div class="sold-out" v-if="isSoldOut(product)">已抢光</div>
        </div>
        <div class="product-info">
          <h3 class="product-name">{{ product.productName }}</h3>
          <div class="price-section">
            <span class="sale-price">¥{{ product.productPrice }}</span>
            <span class="original-price">¥{{ Math.round(product.productPrice * 1.2) }}</span>
          </div>
          <div class="progress-bar">
            <div 
              class="progress" 
              :style="{ width: `${getSoldPercent(product)}%` }"
            ></div>
            <span class="progress-text">已抢{{ getSoldPercent(product) }}%</span>
          </div>
          <button 
            class="buy-btn"
            :class="{ disabled: isProductDisabled(product) }"
            :disabled="isProductDisabled(product)"
            @click="buyNow(product)"
          >
            {{ getButtonText(product) }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { productAPI } from '@/http'
import { useRouter } from 'vue-router'
const router = useRouter()

const buyNow = (product) => {
  router.push({
    name: 'purchasedialog',
    query: {
      product: JSON.stringify(product)
    }
  })
}
// 定义场次数据
const sessions = ref([
  {
    id: 1,
    name: '上午场',
    timeRange: '08:00-12:00',
    startTime: getTodayTime(8),
    endTime: getTodayTime(12),
    productIds: [1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014], // 上午场固定商品ID
    products: [],
    disabled: false
  },
  {
    id: 2,
    name: '下午场',
    timeRange: '12:00-18:00',
    startTime: getTodayTime(12),
    endTime: getTodayTime(18),
    productIds: [1015, 1016, 1017, 1018, 1019, 1020, 1021, 1022], // 下午场固定商品ID
    products: [],
    disabled: false
  },
  {
    id: 3,
    name: '晚间场',
    timeRange: '18:00-24:00',
    startTime: getTodayTime(18),
    endTime: getTodayTime(24),
    productIds: [1023, 1024, 1025, 1026, 1027, 1028, 1029, 1030], // 晚间场固定商品ID
    products: [],
    disabled: false
  }
])

// 当前场次
const currentSession = ref(sessions.value[0])
// 倒计时数据
const hours = ref('00')
const minutes = ref('00')
const seconds = ref('00')
// 定时器
const countdownTimer = ref(null)
// 抢购状态
const saleStatus = ref('coming') // coming/ongoing/ended

// 计算抢购状态文本
const statusText = computed(() => {
  switch(saleStatus.value) {
    case 'coming': return '活动未开始'
    case 'ongoing': return '抢购进行中'
    case 'ended': return '活动已结束'
    default: return ''
  }
})

// 获取当天指定小时的时间戳
function getTodayTime(hours) {
  const date = new Date()
  date.setHours(hours, 0, 0, 0)
  return date.getTime()
}

// 切换抢购场次
function switchSession(session) {
  currentSession.value = session
  startCountdown()
}

// 开始倒计时
function startCountdown() {
  // 清除旧定时器
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value)
  }
  
  // 立即更新一次
  updateCountdown()
  
  // 设置定时器每秒更新
  countdownTimer.value = setInterval(() => {
    updateCountdown()
  }, 1000)
}

// 更新倒计时显示
function updateCountdown() {
  const now = new Date().getTime()
  const startTime = currentSession.value.startTime
  const endTime = currentSession.value.endTime
  
  // 判断当前状态
  if (now < startTime) {
    saleStatus.value = 'coming'
    const distance = startTime - now
    updateTimeDisplay(distance)
  } else if (now >= startTime && now < endTime) {
    saleStatus.value = 'ongoing'
    const distance = endTime - now
    updateTimeDisplay(distance)
  } else {
    saleStatus.value = 'ended'
    hours.value = '00'
    minutes.value = '00'
    seconds.value = '00'
    clearInterval(countdownTimer.value)
  }
  
  // 更新场次禁用状态
  updateSessionStatus()
}

// 更新时间显示
function updateTimeDisplay(distance) {
  // 计算时分秒
  const hoursVal = Math.floor(distance / (1000 * 60 * 60))
  const minutesVal = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60))
  const secondsVal = Math.floor((distance % (1000 * 60)) / 1000)
  
  // 格式化显示
  hours.value = hoursVal.toString().padStart(2, '0')
  minutes.value = minutesVal.toString().padStart(2, '0')
  seconds.value = secondsVal.toString().padStart(2, '0')
}

// 更新场次状态
function updateSessionStatus() {
  const now = new Date().getTime()
  sessions.value.forEach(session => {
    session.disabled = now > session.endTime
  })
}

// 获取商品数据
async function fetchProducts() {
  for (const session of sessions.value) {
    session.products = []
    for (const id of session.productIds) {
      try {
        const response = await productAPI.getProductById(id)
        console.log(`获取商品ID ${id} 成功:`, response)
        session.products.push(response)
      } catch (error) {
        console.error(`获取商品ID ${id} 失败:`, error)
      }
    }
  }
}

// 计算已售百分比
function getSoldPercent(product) {
  if (product.productCount === 0) return 100
  const percent = Math.round((product.productSold / product.productCount) * 100)
  return percent > 100 ? 100 : percent
}

// 是否已售罄
function isSoldOut(product) {
  return product.productCount - product.productSold <= 0
}

// 商品是否禁用
function isProductDisabled(product) {
  return saleStatus.value !== 'ongoing' || isSoldOut(product)
}

// 获取按钮文本
function getButtonText(product) {
  if (saleStatus.value === 'coming') return '未开始'
  if (saleStatus.value === 'ended') return '已结束'
  if (isSoldOut(product)) return '已抢光'
  return '立即抢购'
}

// 根据当前时间自动选择场次
function autoSelectSession() {
  const now = new Date().getTime()
  
  // 查找当前正在进行的场次
  const activeSession = sessions.value.find(session => 
    now >= session.startTime && now < session.endTime
  )
  
  // 如果没有进行中的场次，选择下一个即将开始的场次
  if (!activeSession) {
    const upcomingSessions = sessions.value.filter(
      session => now < session.startTime
    ).sort((a, b) => a.startTime - b.startTime)
    
    currentSession.value = upcomingSessions[0] || sessions.value[0]
  } else {
    currentSession.value = activeSession
  }
}

// 页面加载时初始化
onMounted(() => {
  fetchProducts()
  autoSelectSession()
  startCountdown()
  updateSessionStatus()
})

// 组件销毁前清除定时器
onBeforeUnmount(() => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value)
  }
})
</script>

<style scoped>
.flash-sale-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

.sale-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
  position: relative;
}

.sale-header h2 {
  font-size: 24px;
  color: #333;
  margin: 0;
}

.countdown {
  display: flex;
  align-items: center;
  font-size: 16px;
}

.countdown-title {
  margin-right: 10px;
  color: #666;
}

.countdown-block {
  display: inline-block;
  min-width: 30px;
  padding: 5px;
  background: #e4393c;
  color: white;
  text-align: center;
  border-radius: 3px;
  font-weight: bold;
}

.countdown-colon {
  margin: 0 5px;
  color: #e4393c;
  font-weight: bold;
}

.sale-status {
  position: absolute;
  right: 20px;
  top: 50px;
  color: #e4393c;
  font-weight: bold;
}

.sale-sessions {
  display: flex;
  margin-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.sale-sessions > div {
  flex: 1;
  text-align: center;
  padding: 15px 0;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  transition: all 0.3s;
}

.sale-sessions > div:hover:not(.disabled) {
  color: #e4393c;
}

.sale-sessions > div.active {
  color: #e4393c;
  border-bottom-color: #e4393c;
  font-weight: bold;
}

.sale-sessions > div.disabled {
  color: #999;
  cursor: not-allowed;
}

.sale-sessions small {
  font-size: 12px;
}

.sale-sessions > div.active small,
.sale-sessions > div:hover:not(.disabled) small {
  color: #e4393c;
}

.sale-sessions > div.disabled small {
  color: #ccc;
}

.sale-products {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.sale-product {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
}

.sale-product:hover:not(.disabled) {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.sale-product.disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.product-image {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s;
}

.sale-product:hover:not(.disabled) .product-image img {
  transform: scale(1.05);
}

.sale-tag {
  position: absolute;
  top: 10px;
  left: 0;
  background: #e4393c;
  color: white;
  padding: 3px 10px;
  font-size: 12px;
  border-radius: 0 4px 4px 0;
}

.sold-out {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  font-weight: bold;
}

.product-info {
  padding: 15px;
}

.product-name {
  font-size: 16px;
  margin: 0 0 10px;
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.price-section {
  margin: 10px 0;
}

.sale-price {
  font-size: 20px;
  color: #e4393c;
  font-weight: bold;
  margin-right: 10px;
}

.original-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
}

.progress-bar {
  height: 20px;
  background: #f5f5f5;
  border-radius: 10px;
  margin: 15px 0;
  position: relative;
  overflow: hidden;
}

.progress {
  height: 100%;
  background: linear-gradient(to right, #ff9000, #ff5000);
  border-radius: 10px;
}

.progress-text {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  text-align: center;
  font-size: 12px;
  line-height: 20px;
  color: white;
}

.buy-btn {
  width: 100%;
  padding: 10px 0;
  background: #e4393c;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background 0.3s;
}

.buy-btn:hover:not(.disabled) {
  background: #c91623;
}

.buy-btn.disabled {
  background: #cccccc;
  cursor: not-allowed;
}
</style>